/*  
Copyright Microsoft Corporation

Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at 

http://www.apache.org/licenses/LICENSE-2.0 

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 
MERCHANTABLITY OR NON-INFRINGEMENT. 

See the Apache 2 License for the specific language governing permissions and
limitations under the License. */

using System;
using System.Linq;
using System.Web.Mvc;
using MileageStats.Domain.Models;
using MileageStats.Web.Authentication;
using System.Net;
using MileageStats.Domain.Handlers;
using MileageStats.Web.Properties;

namespace MileageStats.Web.Controllers
{
    [Authorize]
    public class ProfileController : BaseController
    {
        private readonly GetCountries _getCountries;
        private readonly IFormsAuthentication _formsAuthentication;
        private readonly UpdateUser _updateUser;
        
        public ProfileController(
            UpdateUser updateUser,
            GetUserByClaimId getUser,
            GetCountries getCountries,
            IFormsAuthentication formsAuthentication)
            : base(getUser, null)
        {
            _updateUser = updateUser;
            _getCountries = getCountries;
            _formsAuthentication = formsAuthentication;
        }

        [HttpGet]
        public ActionResult Edit()
        {
            return SetupProfileForm(CurrentUser);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Edit(User user, string action = null)
        {
            if (action == "cancel")
            {
                //Reset user profile with current user info
                user.Country = CurrentUser.Country;
                user.DisplayName = CurrentUser.DisplayName;
            }
                
            user.UserId = CurrentUserId;
            user.HasRegistered = true;
                
            _updateUser.Execute(user);

            var ticket = _formsAuthentication.GetAuthenticationTicket(HttpContext);

            if (ticket != null)
            {
                _formsAuthentication.SetAuthCookie(HttpContext,
                    UserAuthenticationTicketBuilder.CreateAuthenticationTicket(
                    user, ticket.IssueDate, ticket.IsPersistent));
            }

            if (ModelState.IsValid || action == "cancel")
            {
                if (Request.IsAjaxRequest())
                    return new HttpStatusCodeResult((int)HttpStatusCode.OK, Messages.ProfileController_ProfileUpdated);

                if(action != "cancel")
                {
                    this.SetConfirmationMessage(Messages.ProfileController_ProfileUpdated);
                }

                return RedirectToAction("Index", "Dashboard");
            }

            if (Request.IsAjaxRequest())
                return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest, Messages.ProfileController_InvalidData);

            return SetupProfileForm(user);
        }

        private ActionResult SetupProfileForm(User user)
        {
            ViewBag.CountryList = _getCountries.GetCountrySelectList();

            return new ContentTypeAwareResult(user);
        }
    }
}